// Include some libs
#include <Ds3234.h>
#include <SPI.h>

// Define constants
#define CS 53				// SS pin on RTC

// Initialize libs
Ds3234 rtc(CS);

void printRegisters() {
	// Print registers
	Serial.print("00h: ");
	Serial.println(rtc.STB_ReadAdr(0x00), BIN);
	Serial.print("01h: ");
	Serial.println(rtc.STB_ReadAdr(0x01), BIN);
	Serial.print("02h: ");
	Serial.println(rtc.STB_ReadAdr(0x02), BIN);
	Serial.print("03h: ");
	Serial.println(rtc.STB_ReadAdr(0x03), BIN);
	Serial.print("04h: ");
	Serial.println(rtc.STB_ReadAdr(0x04), BIN);
	Serial.print("05h: ");
	Serial.println(rtc.STB_ReadAdr(0x05), BIN);
	Serial.print("06h: ");
	Serial.println(rtc.STB_ReadAdr(0x06), BIN);
	Serial.print("07h: ");
	Serial.println(rtc.STB_ReadAdr(0x07), BIN);
	Serial.print("08h: ");
	Serial.println(rtc.STB_ReadAdr(0x08), BIN);
	Serial.print("09h: ");
	Serial.println(rtc.STB_ReadAdr(0x09), BIN);
	Serial.print("0Ah: ");
	Serial.println(rtc.STB_ReadAdr(0x0A), BIN);
	Serial.print("0Eh: ");
	Serial.println(rtc.STB_ReadAdr(0x0E), BIN);
	Serial.print("0Fh: ");
	Serial.println(rtc.STB_ReadAdr(0x0F), BIN);
}

bool isAlarmActive() {
	return rtc.STB_IsINTActiv();
}

bool isAlarmEnabled() {
	return rtc.STB_IsINTEnabled();
}

void setDateAndTime(byte year, byte month, byte day, byte hour, byte minutes, byte second) {
	// If time has not been set this code can be used:
	// Set Date (year, month, date)
	// ex. 2011/9/9
	rtc.SetDate(year, month, day);
	// Set Time (ampm, hour, minute, sec)
	// ex. PM 2:25:30
	// rtc.SetTime(20, 50, 0);
	// ex. 16:20;25
	rtc.SetTime(hour, minutes, second);
	// Serial.print("RTC Hour Mode:");
	// Serial.println(rtc.GetHourMode());
}

void clearAlarm() {
	// Call through to lib
	rtc.STB_ClearAlarm1();
}

int setSecAlarm(int sekunder){
	if (sekunder > 59) return 1;
	uint8_t year, month, date, day, hour, minute, sec;
	// First get the current date and time from RTC
	rtc.GetDate(year, month, date, day);
	rtc.GetTime(hour, minute, sec);
	if (sec + sekunder > 59) {
		sec = sekunder - (60 - sec);
		if (++minute > 59) {
			if (++hour > 24) {
				hour = 0;
				if (++day > 7) {
					day = 0;
				}
			}
		} else {
			sec = sec + sekunder;
		}
	} else {
		sec = sec + sekunder;
	}
	rtc.STB_SetAlarm1(day, hour, minute, sec);
	return 0;
}

int setMinuteAlarm(int minutter){
	if (minutter > 59) return 1;
	uint8_t year, month, date, day, hour, minute, sec;
	// First get the current date and time from RTC
	rtc.GetDate(year, month, date, day);
	rtc.GetTime(hour, minute, sec);
	if (minute + minutter > 59) {
		minute = minutter - (60 - minute);
		if (++hour > 24) {
			hour = 0;
			if (++day > 7) {
				day = 0;
			}
		}
	} else {
		minute = minute + minutter;
	}
	Serial.print("Dato: ");
	Serial.println(date);
	rtc.STB_SetAlarm1(day, hour, minute, sec);
	return 0;
}


